import datetime
import time
from iotdb.Session import Session

from utils.config import Config
from utils.logger import Logger

logger = Logger('Iot').getlogger()


class Iot():
    def __init__(self):
        self.config = Config('./conf/config.ini')
        self.ip = self.config.read_value('iot', 'ip')
        self.port_ = self.config.read_value('iot', 'port')
        self.username_ = self.config.read_value('iot', 'username')
        self.password_ = self.config.read_value('iot', 'password')
        self.session = None  # 初始化session变量

    # 创建一个与IoTDB服务器的会话
    def comm(self):
        if self.session is None:
            self.session = Session(self.ip, self.port_, self.username_, self.password_)
            self.session.open(False)
        return self.session

    # 获取某个产品下的所有设备列表
    def get_device_list(self, tenantid, product):
        session = self.comm()
        query = f"show devices root.{tenantid}.{product}.*"
        result = session.execute_query_statement(query)

        # 处理查询结果
        column_names = result.get_column_names()
        column_count = len(column_names)

        device_list = []
        # 打印数据
        while result.has_next():
            # 获取结果集中的下一行数据
            row = result.next()

            # 获取行数据
            devicename = row.get_fields()

            for i in range(column_count):
                value = str(devicename[i])
                a = value.split('.')[-1]
                device_list.append(a)
        return device_list

    # 获取某台设备最新的数据
    def get_dev_data(self, Field, tenantid, product, devicename):
        # 执行查询操作  13hf1TfUT
        session = self.comm()
        # 想输出几行可以把 更改查询字段pm pm25
        query = f"select Time,{Field} from root.{tenantid}.{product}.{devicename} order by Time desc limit 1"
        result = session.execute_query_statement(query)

        # 判断是否有查询结果
        if not result.has_next():
            print(f" {devicename}查询结果为空------------")
        else:
            # 处理查询结果
            column_names = result.get_column_names()
            column_count = len(column_names)

            # n_row = 0
            # 打印数据
            # while result.has_next():
            # n_row += 1
            # print(f"第 {n_row} 行------------")

            # 获取结果集中的下一行数据
            row = result.next()

            # 获取行数据时间
            time = row.get_timestamp()
            timestamp = time / 1000  # 假设时间戳单位是毫秒，除以 1000 转换为秒

            # 使用 fromtimestamp 方法将时间戳转换为 datetime 对象
            dt = datetime.datetime.fromtimestamp(timestamp)

            # 将 datetime 对象格式化为字符串
            formatted_time = dt.strftime("%Y-%m-%d %H:%M:%S")

            # 获取行数据
            row_data = row.get_fields()
            row_data = [formatted_time] + row_data  # 将时间戳字段添加到行数据中
            # print(row_data)

            # 输出每个字段及其对应的值
            if len(row_data) != column_count:
                print(f"查询结果列数({len(row_data)})与期望({column_count})不符")
                # print(f"查询语句：{query}")
                # print(f"查询结果：{fields}")
                # break

            for i in range(column_count):
                value = row_data[i]
                print(f"{column_names[i]}: {value}")
            self.close()

    # 获取同一产品下多台设备的最新信息
    def get_multi_dev_data(self, Field, tenantid, product):
        device_list = self.get_device_list(tenantid, product)
        n = len(device_list)
        # print(f" {device_list}------------")
        print(f" {product}有{n}个设备-----------")
        n_row = 0
        for devicename in device_list:
            n_row += 1
            # print(f"第 {n_row} 行------------")
            self.get_dev_data(Field, tenantid, product, devicename)

    def dml_dev_data(self, tenantid, product, Field,hours):
        session = self.comm()

        # 时间序列路径
        path = f"root.{tenantid}.{product}.*.{Field}"

        # 计算时间范围
        current_time_millis = int(time.time() * 1000)  # 当前时间（毫秒）
        six_hours_ago_millis = current_time_millis - (hours * 60 * 60 * 1000)  # 6小时前的时间（毫秒）

        # 执行删除操作
        try:
            session.delete_data_in_range([path], six_hours_ago_millis, current_time_millis)
            print("Data deletion successful.")
        except Exception as e:
            print(f"An error occurred: {e}")
        finally:
            # 关闭会话
            self.close()

    # 删除设备
    def dml_dev(self):
        session = self.comm()
        path = "root.U0006.kqjczddt.{dev_name}"
        session.delete_storage_group(path)

    def close(self):
        # 关闭会话
        if self.session is not None:
            self.session.close()
            self.session = None

# rs=Iot()
# rs.dml_dev()